# libs ----
library(sf)
library(geomander)
library(tidyverse)
library(redist)
library(ppmf)
library(patchwork)
library(wacolors)
readr::local_edition(1)
# paths
ppmf19_path <- "data-raw/ppmf_19.csv"
ppmf12_path <- "data-raw/ppmf_12.csv"
ppmf4_path <- "data-raw/ppmf_04.csv"

# helper ----
source('R/00_custom_functions.R')

# data ----
ppmf19 <- read_ppmf('NY', ppmf19_path)
ppmf12 <- read_ppmf('NY', ppmf12_path)
ppmf4 <- read_ppmf('NY', ppmf4_path)

# subset
ppmf19 <- ppmf19 %>% filter(TABBLKCOU == '087')
ppmf12 <- ppmf12 %>% filter(TABBLKCOU == '087')
ppmf4 <- ppmf4 %>% filter(TABBLKCOU == '087')

# agg
ppmf19 <- ppmf19 %>% add_geoid() %>% agg()
ppmf19 <- ppmf19 %>%
    rename_with(~ add_pref(.x,pref = 'v19'), starts_with(c('pop', 'vap')))
ppmf12 <- ppmf12 %>% add_geoid() %>% agg()
ppmf12 <- ppmf12 %>%
    rename_with(~ add_pref(.x,pref = 'v12'), starts_with(c('pop', 'vap')))
ppmf4 <- ppmf4 %>% add_geoid() %>% agg()
ppmf4 <- ppmf4 %>%
    rename_with(~ add_pref(.x,pref = 'v4'), starts_with(c('pop', 'vap')))

# add comparison
census <- create_block_table('NY', 'Rockland')

# join ----
tb <- census %>%
    left_join(ppmf19, by = 'GEOID') %>%
    left_join(ppmf12, by = 'GEOID') %>%
    left_join(ppmf4, by = 'GEOID')
# set nas to 0
tb[is.na(tb)] <- 0

# subset ----
er_geoids <- readRDS('data/ERCSD/er_geoids.Rds')
er <- tb %>% filter(GEOID %in% er_geoids)
er <- er %>% mutate(rn = row_number())

# Add enacted wards ----
man <- readxl::read_xlsx('data/ERCSD/ercsd_manual_block_dists.xlsx',
                         col_names = c('rn', 'ward'))

er <- er %>% left_join(man, by = 'rn')
saveRDS(object = er, 'data/ERCSD/er_merged_19.Rds', compress = 'xz')

# compare parity ----
er %>%
    st_drop_geometry() %>%
    group_by(ward) %>%
    summarize(pop = sum(pop), v19_pop = sum(v19_pop), v12_pop = sum(v12_pop), v4_pop = sum(v4_pop)) %>%
    summarize(across(where(is.numeric), \(x){max(abs(x - mean(x)))}))
